package com.hqd.jjvm.classpath;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.ClassUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类读取器
 *
 * @author hqd
 */
@NoArgsConstructor
@Getter
public class ClassParse {

    private ClassResource classResource;

    public ClassParse(ClassResource classResource) {
        this.classResource = classResource;
    }

    public boolean isExists(String className) {
        if (!className.endsWith(ClassResource.CLASS_FILE_SUFFIX)) {
            className = className.replaceAll("\\.", "/");
        } else {
            className = ClassUtil.getPackagePath(className);
        }
        className += ClassResource.CLASS_FILE_SUFFIX;
        return classResource.isExists(className);
    }

    public Map<String, ClassFile> parseAll() throws IOException {
        List<ClassFileInfo> list = classResource.readAllClass();
        Map<String, ClassFile> classFileMap = new HashMap<>(list.size());
        for (ClassFileInfo classFileInfo : list) {
            ClassFile classFile = new ClassFile(classFileInfo);
            String className = classFileInfo.getFileName().substring(0, classFileInfo.getFileName().lastIndexOf("."));
            classFileMap.put(className, classFile);
        }
        return classFileMap;
    }

    public ClassFile parseClass(String className) throws IOException {
        className = className.replaceAll("\\.", "/");
        ClassFileInfo classFileInfo = classResource.readClass(className + ClassResource.CLASS_FILE_SUFFIX);
        if (classFileInfo != null) {
            return new ClassFile(classFileInfo);
        }
        return null;

    }
}
